package com.dongdongshop.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /*创建shirofilterFactoryBean
    * */

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro内置过滤器
        /*
        shiro内置过滤器，可以实现权限相关的拦截器
        常用的过滤器有以下：
                1.anon：无需认证（登录）可以访问
                2.authc:必须认证才可以访问
                3.user:如果使用rememberMe的功能可以直接访问
                4.perms:该资源必须得到资源权限才可以访问
                5.role:该资源必须得到角色权限才可以访问
        * */
        Map<String,String> filterMap = new LinkedHashMap<String,String>();
        filterMap.put("/**", "anon");
       /* filterMap.put("/user/**", "anon");
        filterMap.put("/index/toRegister", "anon");
        filterMap.put("/**","authc");
        //修改调整登录页面

        shiroFilterFactoryBean.setLoginUrl("/index/toLogin");
        //设置无权访问页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/user/Unauthorized");*/
        //退出登录
        filterMap.put("/auth/logout", "logout");
        //被拦截后打回的页面
        shiroFilterFactoryBean.setLoginUrl("/user/toLogin");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    /*创建defaultWebSecurityManager
    * */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm对象
        securityManager.setRealm(realm);
        return securityManager;
        }

    /*创建realm类
    * */
    @Bean
    public Realm getRealm(@Autowired HashedCredentialsMatcher credentialsMatcher){
        Realm realm = new Realm();
        realm.setCredentialsMatcher(credentialsMatcher);
        return realm;
    }

    //设置加密组件
    @Bean
    public HashedCredentialsMatcher getHashedCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new  HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");//设置加密方式
        //只能加密次数
        credentialsMatcher.setHashIterations(10);
        //开启hex编码方式
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
